var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../services/user.js');
var QR = require("../../utils/qrcode.js");
var app = getApp();

Page({
    data: {
        tabs: [],
        activeTab: 0,
        defineNum: 4,
        content: [],
        startDate: "",
        endDate: "",
        pickEndDate: "",
        showPicker: false,
        timeParams: [],
        pageSize:10,
        pageNo:1,
        orderList:[],
        hasMore:true,
        status:1,
        layShow: false,
        maskHidden: true,
        imagePath: '',
        placeholder: '' //默认二维码生成文本
    },
  
    onPullDownRefresh: function () {
        this.getData(this.data.status)
    },
    onLoad() {
        // const titles = ['待使用', '已使用', '售后']
        // const tabs = titles.map(item => ({title: item}))
        // this.setData({tabs})
        const titles = ['待使用', '已使用', '售后']
        const tabs = titles.map(item => ({title: item}))
        let content = titles.map(item => ({title: item}))
        this.setData({tabs, content})
        this.getData(this.data.status)

        
    },
    onRefund(e){
        let _this = this
        let $id = e.currentTarget.dataset.id
        console.log($id)
        wx.showModal({
            title: '提示',
            content: '确定申请退款吗？',
            success (res) {
                if (res.confirm) {
                    wx.showLoading({
                        title: '加载中...',
                    })
                    util.request(api.surroundings.userRefund+'/'+$id,{},'post').then(res=>{
                        wx.showToast({
                          title: '申请退款成功，请等待审核～',
                        })
                        _this.getData(this.data.status)
                        wx.hideLoading()
                    }).catch(err=>{
                        console.log(err)
                        wx.hideLoading()
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    openLay(e){
        let that = this
        var url = e.currentTarget.dataset.id.toString() 
        //console.log(url)
        that.setData({
            maskHidden: false,
        });
        wx.showToast({
            title: '生成中...',
            icon: 'loading',
            duration: 2000
        });
        var st = setTimeout(function () {
            wx.hideToast()
            var size = that.setCanvasSize();
            //绘制二维码
            that.createQrCode(url, "mycanvas", size.w, size.h);
            that.setData({
                maskHidden: true
            });
            clearTimeout(st);
        }, 2000)
    },
    //适配不同屏幕大小的canvas
    setCanvasSize: function () {
        var size = {};
        try {
        var res = wx.getSystemInfoSync();
        var scale = 750 / 686; //不同屏幕下canvas的适配比例；设计稿是750宽
        var width = res.windowWidth / scale;
        var height = width; //canvas画布为正方形
        size.w = width;
        size.h = height;
        } catch (e) {
        // Do something when catch error
        console.log("获取设备信息失败" + e);
        }
        return size;
    },
    createQrCode: function (url, canvasId, cavW, cavH) {
        //调用插件中的draw方法，绘制二维码图片
        QR.api.draw(url, canvasId, cavW, cavH, this, this.canvasToTempImage);
        // setTimeout(() => { this.canvasToTempImage();},100);

    },
    //获取临时缓存照片路径，存入data中
    canvasToTempImage: function () {
        var that = this;
        wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res) {
            var tempFilePath = res.tempFilePath;
            console.log(tempFilePath);
            that.setData({
                imagePath: tempFilePath,
                layShow: true
            });
        },
        fail: function (res) {
            console.log(res);
        }
        }, that);
    },
    //点击图片进行预览，长按保存分享图片
    previewImg: function (e) {
        var img = this.data.imagePath;
        wx.previewImage({
        current: img, // 当前显示图片的http链接
        urls: [img] // 需要预览的图片http链接列表
        })
    },
    onCloseLay(){
        this.setData({
            layShow:false
        })
    },
    onReachBottom(){
        this.loadMore(this.data.status)
    },
    onCall(e){
        wx.makePhoneCall({
          phoneNumber: e.currentTarget.dataset.tel,
        })
    },
    getData(status){
        let _this = this;
        _this.setData({
            pageNo: 1,
            hasMore:true
        });
        wx.showLoading({
            title: '加载中...',
          })
        util.request(api.surroundings.getOrderList,{
            pageNo:_this.data.pageNo,
            pageSize:_this.data.pageSize,
            status:status
        },'get').then(res=>{
            _this.setData({
                orderList: res.result
            });
            if (res.result.length < this.data.pageSize) {
                _this.setData({
                    hasMore: false,
                })
            }
            wx.stopPullDownRefresh();
            wx.hideLoading()
        }).catch(err=>{
            console.log(err)
            wx.hideLoading()
            wx.stopPullDownRefresh() 
        })
    },
    loadMore: function(status) {
        var that = this;
        if (!this.data.hasMore) return
        wx.showLoading({
            title: '加载中...',
        })
        var url = api.surroundings.getOrderList + "?pageNo=" + (++that.data.pageNo) + '&pageSize=' + that.data.pageSize+ '&status=' + status;
        util.request(url,'get').then(function(res) {
            if (res.code == 200) {
                that.setData({
                    orderList: that.data.orderList.concat(res.result)
                });
                if (res.result.length < that.data.pageSize) {
                    that.setData({
                        hasMore: false,
                    })
                }
                wx.hideLoading()
            }
        });
    },
    onChange(e) {
        const index = e.detail.index
        this.setData({
            activeTab: index
        })
    },
    switchTab(e){
        const id = e.currentTarget.dataset.id;
        this.setData({
            activeTab: id
        })
        if(this.data.activeTab === 0){
            this.setData({
                status:1
            })
        } else if(this.data.activeTab === 1){
            this.setData({
                status:2
            })
        } else if(this.data.activeTab === 2){
            this.setData({
                status:9
            })
        }
        this.getData(this.data.status)
    },
  
})
  